/**
 * 
 */
package com.williamoneil.charts.client.widget;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.canvas.dom.client.Context2d;
import com.williamoneil.charts.client.data.BenchmarkAxis;
import com.williamoneil.charts.client.data.ChartBoundsRect;
import com.williamoneil.charts.client.data.ChartElementsData;
import com.williamoneil.charts.client.data.DateAxis;
import com.williamoneil.charts.client.data.LineData;
import com.williamoneil.charts.client.data.Tick;
import com.williamoneil.charts.client.util.ColorEntityType;
import com.williamoneil.charts.client.util.Colors;

/**
 * @author gudipati
 *
 */
public class BenchmarkLineLayer extends ChartOverlay {
	
	public BenchmarkLineLayer(final ChartBoundsRect chartBounds) {
		super(chartBounds);
	}
	
	/* (non-Javadoc)
	 * @see com.williamoneil.charts.client.widget.ChartOverlay#drawOverlay()
	 */
	@Override
	public void drawOverlay() {
		final ChartElementsData elements = super.getChartElements();
		if(elements == null || elements.getBenchmarkAxis() == null) {
			return;
		}
		
		drawBenchmarkLine();
	}
	
	private void drawBenchmarkLine() {
		final ChartElementsData elements = super.getChartElements();
		final DateAxis dateAxis = elements.getDateAxis();
		final ChartBoundsRect bounds = super.getChartBoundsRect();
		final BenchmarkAxis benchmarkAxis = elements.getBenchmarkAxis();
		final Context2d context = super.getGraphicsContext();

		final List<LineData> lineList = new ArrayList<LineData>();
		for(final Tick aData : elements.getTicks()) {
			if(aData.getBenchmarkLine() == null) {
				continue;
			}
			
			final int x = dateAxis.getX(aData.getDate());
			if(!bounds.isXWithinBounds(x)) {
				break;
			}
				
			final int y = benchmarkAxis.getY(aData.getBenchmarkLine().getPrice(), bounds);
					
			final LineData ma = new LineData(x, y);
			lineList.add(ma);
		}
		
		if(lineList.size() > 0) {
			context.beginPath();
			String color = Colors.getColorTheme().getColor(ColorEntityType.BENCHMARK_LINE);
			context.setStrokeStyle(color);
			context.setFillStyle(color);

			context.moveTo(lineList.get(0).getX(), lineList.get(0).getY());
			for(int i=0;i<lineList.size();i++) {
				final LineData aData = lineList.get(i);
				context.lineTo(aData.getX(), aData.getY());
			}
			context.stroke();
		}
	}
}